#!/usr/bin/python
# -*- coding: utf-8 -*-

#为方便以后移植，参数中的 key 一律为字符串格式
import datetime
import math

import geobox
import logging

from google.appengine.ext import db
from google.appengine.api import memcache 
from google.appengine.api import users

import googledatabase
import getcounter
#import function_public

USER_INFO_ID_COUNT_NAME = 'UserInfoIDCount'


#-------------------------地图常量---------------------
RADIUS = 6378100

GEOBOX_CONFIGS = (
  (4, 5, True),
  (3, 2, True),
  (3, 8, False),
  (3, 16, False),
  (2, 5, False),
)

def GetGeoBoxList(Latitude, Longitude):
    AllBoxes = []
    for (resolution, slice, use_set) in GEOBOX_CONFIGS:
        if use_set:
            AllBoxes.extend(geobox.compute_set(Latitude, Longitude, resolution, slice))
        else:
            AllBoxes.append(geobox.compute(Latitude, Longitude, resolution, slice))

    return AllBoxes;


def AccountEarthDistance(lat1, lon1, lat2, lon2):
  lat1, lon1 = math.radians(float(lat1)), math.radians(float(lon1))
  lat2, lon2 = math.radians(float(lat2)), math.radians(float(lon2))
  return RADIUS * math.acos(math.sin(lat1) * math.sin(lat2) +
      math.cos(lat1) * math.cos(lat2) * math.cos(lon2 - lon1))

#MaxResults 最多返回个数
#MinParams 最少参数个数   ？不知作用
#注意，返回的不是记录集，而是 LoginName 对应的 UserItem 的字典
def GetNearbyUser(Latitude, Longitude, MaxResults=500, MinParams=(2,0)):
    FoundUser = {}
    for Params in GEOBOX_CONFIGS:
        if len(FoundUser) >= MaxResults:
            break
        if Params < MinParams:
            break

        resolution, slice, unused = Params
        Box = geobox.compute(Latitude, Longitude, resolution, slice)
#        logging.error("--------------GetNearbyUser for box=%s at resolution=%s, slice=%s", Box, resolution, slice)
        
        Query = db.GqlQuery( 'SELECT * FROM CUserTable WHERE GeoBoxes = :1', Box)
        Results = Query.fetch(50)
    
#        logging.error("--------------------GetNearbyUser Found %d results", len(Results))

        # De-dupe results.
        for UserItem in Results:
            if UserItem.LoginName not in FoundUser:
                FoundUser[UserItem.LoginName] = UserItem

    return FoundUser


def GetOneUserInfo(LoginID):
    Query = db.GqlQuery('SELECT * FROM CUserTable WHERE LoginID = :1', LoginID)
    return Query.get()


def GetOneUserNickName(LoginID):
    if LoginID:
        RetName = LoginName
        OneUserInfo = GetOneUserInfo(LoginID)
        if OneUserInfo:
            return OneUserInfo.LoginAccount.nickname()
        else:
            return ''
    else:
        return ''
    
#def GetOneUserInfoFromNickName(NickName):
#    Query = db.GqlQuery('SELECT * FROM CUserTable WHERE NickName = :1', NickName)
#    return Query.get()


#def GetOneUserInfoFromLoginOrNickName(LoginOrNickName, LoginFirst = True):
#    UserInfo = None
#    if LoginFirst:
#        UserInfo = GetOneUserInfo(LoginOrNickName)
#        if UserInfo == None:
#            UserInfo = GetOneUserInfoFromNickName(LoginOrNickName)
#    else:
#        UserInfo = GetOneUserInfoFromNickName(LoginOrNickName)
#        if UserInfo == None:
#            UserInfo = GetOneUserInfo(LoginOrNickName)
#
#    return UserInfo


#def GetOneUserLoginNameFromLoginOrNickName(LoginOrNickName, LoginFirst = True):
#    UserInfo = GetOneUserInfoFromLoginOrNickName(LoginOrNickName)
#    LoginName = ''
#    if UserInfo:
#        LoginName = UserInfo.LoginName
#        if LoginName == None:
#            LoginName = ''
#
#    return LoginName



def SetOneUserInfo(UserInfo):
    UserInfo.put()

    if TheItemInMemcacheRecord( 'CUserTable_New', str(UserInfo.key()) ):
        #清理缓存区数据
        memcache.delete('CUserTable_New')
        memcache.delete('CUserTable_PrePage')
        memcache.delete('CUserTable_NextPage')


#检查一个NickName是否已存在
def CheckNickNameIsExist(NickName, LoginName = ''):
    Query = db.GqlQuery('SELECT * FROM CUserTable WHERE NickName = :1', NickName)
    if 0 < len(LoginName):
        Query = db.GqlQuery('SELECT * FROM CUserTable WHERE NickName = :1 AND LoginName != :2', NickName, LoginName)

    Results = Query.fetch(1)
    if Results:
        return True
    else:
        return False


#增加一个用户
def AddCurrentUserToUserTable(Language = ''):
    User = users.get_current_user()
    if User is None:
        return None

    UserInfo = googledatabase.CUserTable()
    UserInfo.ID = getcounter.GetAutoIncrementCount(USER_INFO_ID_COUNT_NAME)
    UserInfo.LoginID = User.user_id()
    UserInfo.LoginAccount = User
    UserInfo.Language = Language
    UserInfo.put()

    #清理缓存区数据
    memcache.delete('CUserTable_New')
    memcache.delete('CUserTable_PrePage')
    memcache.delete('CUserTable_NextPage')
    
    return UserInfo


#增加一个用户的积分        
def AddOneUserIntegral(LoginID, AddIntegral):
    UserInfo = GetOneUserInfo(LoginID)
    if UserInfo:
        publicfunction.AddOnePropertyCount(UserInfo.key(), "Integral", AddIntegral)

    
def GetHotUserRecord(PageSize):
    Query = db.GqlQuery('SELECT * FROM CUserTable ORDER BY Integral DESC')
    return Query.fetch(PageSize)


#检查 FriendLoginName 是否是 UserLoginName 的朋友
def UserIsFriend(UserLoginID, FriendLoginID):
    Query = db.GqlQuery('SELECT * FROM CFriendTable WHERE FriendID = :1 AND LoginID = :2', FriendLoginID, UserLoginID)
    FriendItem = Query.get()
    if FriendItem:
        return True
    else:
        return False
    
    

